package com.asset.modules.budget.service.impl;

import com.asset.modules.assets.model.Asset;
import com.asset.modules.assets.service.AssetService;
import com.asset.modules.budget.mapper.BudgetMapper;
import com.asset.modules.budget.model.Budget;
import com.asset.modules.budget.service.BudgetService;
import com.asset.modules.common.utils.StringUtil;

import com.asset.modules.system.model.Company;
import com.asset.modules.system.model.Project;
import com.asset.modules.system.service.CompanyService;
import com.asset.modules.system.service.ProjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预算服务类
 * @author chenchen
 */
@Service
public class BudgetServiceImpl extends ServiceImpl<BudgetMapper, Budget> implements BudgetService {

    private static final Logger logger = LoggerFactory.getLogger(BudgetServiceImpl.class);

    @Autowired
    CompanyService companyService;

    @Autowired
    ProjectService projectService;

    @Autowired
    AssetService as;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Budget getOneBudget(QueryWrapper<Budget> wrapper) {
       return wrapper.getEntity();
    }


    @Override
    public List<Budget> getListBudget(QueryWrapper<Budget> wrapper) {
        return list(wrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Budget getBudgetById(Long id) {
        QueryWrapper<Budget> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        return getOne(wrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public IPage<Budget> getBudgetPage(Page page, Budget budget) {
        IPage _page;
        QueryWrapper<Budget> queryWrapper = new QueryWrapper();
        List<Budget> results = new ArrayList<>();
        Map params = new HashMap();
        String companyId = budget.getCompanyId();
        Object projectId = budget.getProjectId();
        // -1表示江苏保利
        if(companyId!=null&&companyId.equals("-1")){
            queryWrapper.eq("company_id", "-1");
            _page = page(page, queryWrapper);
            _page.setTotal(count(queryWrapper));
        }else{
            Company c = companyService.getById(budget.getCompanyId());
            Project p = projectService.getById(budget.getProjectId());
            if(budget.getFormerId()!=null){
                params.put("formerId", budget.getFormerId());
            }
            if(budget.getFiscalYear()!=null){
                params.put("fiscal_year", budget.getFiscalYear());
            }
            if(budget.getCompanyId()!=null){
                params.put("company_id", budget.getCompanyId());
            }

            if(budget.getProjectId()!=null){
                params.put("project_id", budget.getProjectId());
            }

            if(budget.getProjectName()!=null){
                params.put("project_name", budget.getProjectName());
            }

            queryWrapper.allEq(params);

            if(budget.getUpdateTime()!=null&&budget.getCreateTime()!=null){
                queryWrapper.between("create_time", budget.getCreateTime(), budget.getUpdateTime());
            }

            _page = page(page, queryWrapper);
            List list = _page.getRecords();
            if(list.size()>0&&projectId!=null&&!projectId.equals("")){
                for(Object o : list){
                    expenditureAndBalance((Budget)o);
                }
            }
            _page.setTotal(count(queryWrapper));
        }
       return _page;
    }


    @Override
    public List<Budget> getBudgetByCompanyId(String companyId) {
        QueryWrapper<Budget> qw = new QueryWrapper<>();
        qw.eq("company_id", companyId);
        List<Budget> budgets = list(qw);
        List<Budget> results = new ArrayList<>();
        Company c = companyService.getById(companyId);
        for(Budget b : budgets){
            Project p = projectService.getById(b.getProjectId());
            if(c!=null){
                b.setCompanyCode(c.getCompanyCode());
                b.setCompanyName(c.getCompanyName());
            }
            if(p!=null) {
                b.setProjectCode(p.getProjectCode());
                b.setProjectName(p.getProjectName());
            }
            b = expenditureAndBalance(b);
            results.add(b);
        }
        return results;
    }


    @Override
    public boolean isExist(String column, String name) {
        QueryWrapper<Budget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, name);
        List<Budget> result = list(queryWrapper);
        if(result.size()>0){
            return true;
        }
        return false;
    }

    /**
     * 计算已花费预算和余额
     * @param b
     * @return
     */
    @Override
    public Budget expenditureAndBalance(Budget b) {
        String projectId = b.getProjectId();
        QueryWrapper<Asset> qw = new QueryWrapper<>();
        qw.eq("substr(buy_time,1,4)", b.getFiscalYear());
        qw.eq("project_id", projectId);
        List<Asset> assets = as.list(qw);
        double expenditure = 0;
        double budgetBalance = 0;
        if(assets.size()>0){
            for(Asset a : assets){
                expenditure += a.getRegisterMoney();
            }
            //预算余额
            budgetBalance = b.getProjectBudget() - expenditure;
        }else{
            expenditure =0;
            budgetBalance = b.getProjectBudget();
        }

        b.setExpenditure(expenditure);
        b.setBudgetBalance(budgetBalance);
        return b;
    }


    /**
     * 根据预算编码获取预算信息
     * @param projectId
     * @return
     */
    @Override
    public List<Budget> getBudgetByProjectId(String projectId) {
        QueryWrapper<Budget> qw = new QueryWrapper<>();
        qw.eq("project_id", projectId);
        List<Budget> budgets = list(qw);
        return budgets;
    }


    /**
     * 验证是否 当前预算大于上级预算
     * @param formerBudget
     * @param currentBudget
     * @param formerId
     * @param year
     * @param type
     * @return
     */
    public boolean verifyLimitedBudget(Double formerBudget, Double currentBudget, String formerId, Object id,String year, String type){
        QueryWrapper<Budget> qw = new QueryWrapper<>();
        qw.eq("fiscal_year", year);
        qw.eq("former_id", formerId);
        qw.eq("type", type);
        List<Budget> budgets = getListBudget(qw);
        Double totalBudget = new Double(0);

        //二级预算
        if(type.equals("2")) {
            for (Budget b : budgets) {
                //排除当前编辑的预算信息，防止重复累加
                if(id==null||!b.getId().equals(id)){
                    totalBudget += Double.valueOf(b.getCompanyBudget());
                }
            }
            //三级预算
        }else if(type.equals("3")){
            for (Budget b : budgets) {
                if(id==null||!b.getId().equals(id)){
                    totalBudget += Double.valueOf(b.getProjectBudget());
                }
            }
        }
        boolean flag = formerBudget<=(totalBudget+currentBudget)? true : false;
        return  flag;
    }
}
